#!/usr/bin/perl -w

use cm2bug;
use Getopt::Long;
use File::Basename;

$_PRG=basename($0);

sub usage {
	print "
Usage: $_PRG --table T [--dbfile D] [--define] [--infile O]
";
	exit(1);
}

$ARG_define=0;
$ARG_dbfile="dbfile";
if(!GetOptions(
	"define"	=> \$ARG_define,
	"dbfile=s"	=> \$ARG_dbfile,
	"table=s"	=> \$ARG_table,
	"infile=s"	=> \$ARG_infile,
)) {
	usage;
}

if(!defined($ARG_table)) { usage; }

$ARG_infile="-" if !defined($ARG_infile);
if($ARG_infile ne "-" && ! -f $ARG_infile) {
	print STDERR "Error: Specified file to read does not exist!\n";
	exit 1;
}

#########################################################################
# Open the database, prepare and execute the statement, ready for 	#
# writing records.							#
#########################################################################

$DBH = cm2bug->new($ARG_dbfile);

if(!defined($DBH)) {
	print STDERR "Error: Unable to open dataase $ARG_dbfile!\n";
	exit 1;
}

#########################################################################
# Attempt to open the input file first.					#
#########################################################################

if(!open($fd,"$ARG_infile")) {
	print STDERR "Error: Unable to open file for reading:\n$!\n";
	exit 1;
}

#########################################################################
# If the table already exists then we also need to ensure all existing	#
# records are removed.							#
#########################################################################

if($ARG_define) {
 	$str=<$fd>;
	chomp $str;
	if($str !~ /^SCHEMA::=/) {
		print STDERR "Error: Table schema not found in dump file!\n";
		exit 1;
	}
	$sql=$str; $sql=~ s/^SCHEMA::=//;
	$sql=pack("H*",$sql);
	$sql =~ s/CREATE TABLE [a-z0-9]+\(/CREATE TABLE $ARG_table(/i;
	$DBH->do($sql);
	($cc,$rc)=$DBH->error;
	if(defined($rc)) {
		print STDERR "Error: Unable to create table '$ARG_table'.\n";
		print STDERR "Error: $rc [rc=$cc]\n";
		exit 1;
	}
	$DBH->commit;
}
		
if(!$DBH->exists("table",$ARG_table)) {
	print STDERR "Error: Table \"$ARG_table\" does not exist.\n";
	exit 1;
}

$cmd="DELETE FROM $ARG_table";
$DBH->do($cmd);
($cc,$rc)=$DBH->error;
if(defined($rc)) {
	print STDERR "Error: Unable to drop records from '$ARG_table'.\n";
	print STDERR "Error: $rc [rc=$cc]\n";
	exit 1;
}
$DBH->commit;

$i=0;
while($str=<$fd>) {
	chomp $str;
	next if $str =~ /^SCHEMA::=/;
	$cmd="";
	%VALUES=();
	@R=split(/,/,$str);
	for $cval (@R) {
		($field,$hex)=split(/:/,$cval);
		$VALUES{$field}=pack("H*",$hex);
	}
	$cmd="INSERT INTO $ARG_table(";
	$cmd.=join(",",(keys %VALUES));
	$cmd.=") VALUES(";
	@L=map { "'$_'"; } (values %VALUES);
	$cmd.=join(",",@L) . ");";
	$DBH->do($cmd);
	($cc,$rc)=$DBH->error;
	if(defined($rc)) {
		print STDERR "Error occured whilst performing:\n$cmd\n";
		print STDERR "Error: $rc [rc=$cc]\n";
		exit 1;
	}
	$i++;
}
close($fd);
$DBH->commit;
print STDERR "$i Record",$i==1 ? "" : "s"," restored.\n";

exit(0);
